#include "AnaDef.h"
#include "XGLUtils.h"

void doNcls(const TString fin, const Bool_t kdL)
{
  TCanvas c1;
  gStyle->SetOptStat(0);
  
  TFile::Open(fin);
  TTree * tree= (TTree*)gDirectory->Get("newdraw_Tree");

  TH2D *h2=new TH2D("h2","", 180, 0, 180, 100,0,5);
  if(kdL){
    h2->SetXTitle("N_{cls}/L");
  }
  else{
    h2->SetXTitle("N_{cls}");
  }

  h2->SetYTitle("Q55/<Q55>");

  const TString cut = "trdnch0==6";

  if(kdL){
    tree->Draw("trdQ0/AliTRDdEdxBaseUtils::Q0MeanTRDpp(pow(10, ltbg)):trdncls0/(anguCorr0+anguCorr1)*2>>h2",cut,"colz");
  }
  else{
    tree->Draw("trdQ0/AliTRDdEdxBaseUtils::Q0MeanTRDpp(pow(10, ltbg)):trdncls0>>h2",cut,"colz");
  }

  TH2D *h3=XGLUtils::NormalHist(h2,50,1);
  h3->Draw("colz");
  gPad->SetGrid();

  TH1D *hnor=0, *hmpv=0, *hwid=0, *hres=0, *hchi=0;
  XGLUtils::FitSlicesY(h2, 0x0, hnor, hmpv, hwid, hres, hchi, 50, 0, 0.99);

  TH1D *hs[]={hnor, hmpv, hwid, hres, hchi};

  TFile *fout=new TFile(Form("ncls_kdL%d.root", kdL),"recreate");
  h2->Write();
  h3->Write();

  for(int ii=0; ii<5; ii++){
    hs[ii]->Draw();
    //c1.Print(Form("%s.png",hs[ii]->GetName()));
    hs[ii]->Write();
  }
  
  fout->Save();
  fout->Close();
}

int main(int argc, char * argv[])
{
  for(int ii=0; ii<argc; ii++){
    printf("%d: %s\n", ii, argv[ii]);
  }

  doNcls(argv[1], atoi(argv[2]));

  return 0;
}
